package io.renren.modules.forYoung.controller;

import io.renren.common.annotation.Login;
import io.renren.common.utils.R;

import io.renren.common.config.ConstantConfig;
import io.renren.common.config.Contant;
import io.renren.common.config.SensitiveWordFilter;
import io.renren.modules.forYoung.entity.ForYoungComment;
import io.renren.modules.forYoung.entity.ForYoungReply;
import io.renren.modules.forYoung.entity.ForYounyEntity;
import io.renren.modules.forYoung.service.ForYounyService;
import io.renren.modules.news.service.NewsService;
import io.renren.modules.personal.service.PersonalService;
import io.renren.modules.sys.dto.AttentionAndFansDto;
import io.renren.modules.sys.entity.*;
import io.renren.modules.sys.service.*;
import io.renren.common.utils.Jdpush;
import io.renren.common.utils.Util;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@RestController
@RequestMapping("/api/young")
public class ForYoungController {

    @Autowired
    ForYounyService forYounyService;
    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;
    @Autowired
    PersonalService personalService;
    @Autowired
    Contant contant;
    @Autowired
    NewsService newsService;


    /*private void SetUTF(List<ForYounyEntity> list) throws UnsupportedEncodingException {
        for(ForYounyEntity f:list){
            f.setTitle(new String(f.getTitle().getBytes(),"UTF-8"));
        }
    }*/

    @Login
    @PostMapping("getCommentList")
    @ApiOperation("信息列表")
    public R getCommentList(@RequestBody Map<String, Object> params, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        params.put("userId", userId);
        Util.SetPage(params);
        TimeZone tz = TimeZone.getTimeZone("ETC/GMT-8");
        TimeZone.setDefault(tz);
        List<ForYoungComment> list = forYounyService.getCommentList(params);

        return R.ok(msg, code).put("list", list).put("nextPage", params.get("nextPage"));
    }

    @Login
    @PostMapping("getReplyList")
    @ApiOperation("获取回复信息列表")
    public R getReplyList(@RequestBody Map<String, Object> params, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        params.put("userId", userId);
        Util.SetPage(params);
        List<ForYoungReply> list = forYounyService.getReplyList(params);

        return R.ok(msg, code).put("list", list).put("nextPage", params.get("nextPage"));
    }

    @Login
    @PostMapping("getListByDistance")
    @ApiOperation("获取附近信息列表")
    public R getListByDistance(@RequestBody Map<String, Object> params, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        List<ForYounyEntity> forYounyEntityList = forYounyService.getListByDistance(params);
        for (ForYounyEntity forYounyEntity : forYounyEntityList) {
            if (forYounyEntity.getDistance() < 1) {
                forYounyEntity.setDistanceStr(forYounyEntity.getDistance() * 1000 + "m");
            } else {
                forYounyEntity.setDistanceStr(forYounyEntity.getDistance() + "km");
            }
        }
        return R.ok(msg, code).put("list", forYounyEntityList);
    }


    @Login
    @PostMapping("getList")
    @ApiOperation("获取信息列表")
    public R collect(@RequestBody Map<String, Object> params, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        String type = (String) params.get("type");
        if ("推荐".equals(type)) {
            params.remove("type");
            List list = forYounyService.getMyRecommendList(params);
            return R.ok(msg, code).put("list", list);
        } else if ("视频".equals(type)) {
            List list = forYounyService.getMyRecommendList(params);
            return R.ok(msg, code).put("list", list);
        } else if ("大学生活".equals(type)) {
            List list = forYounyService.getMyRecommendList(params);
            return R.ok(msg, code).put("list", list);
        } else if ("学习分享".equals(type)) {
            List list = forYounyService.getMyRecommendList(params);
            return R.ok(msg, code).put("list", list);
        } else if ("资讯/活动".equals(type)) {
            //List list = forYounyService.getMyRecommendList(params);
            List list = newsService.getNewsByTypeNoPage(params);
            return R.ok(msg, code).put("list", list);
        } else if ("升本/考研".equals(type)) {
            //List list = forYounyService.getMyRecommendList(params);
            List list = newsService.getNewsByTypeNoPage(params);
            return R.ok(msg, code).put("list", list);
        } else if ("就业/培训".equals(type)) {
            //List list = forYounyService.getMyRecommendList(params);
            List list = newsService.getNewsByTypeNoPage(params);
            return R.ok(msg, code).put("list", list);
        }
        return R.ok(msg, code);
    }


    @Login
    @PostMapping("getSeachList")
    @ApiOperation("获取信息列表")
    public R getSeachList(@RequestBody Map<String, Object> params, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        boolean isUser = (boolean) params.get("isUser");
        if (!isUser) {
            Util.SetPage(params);
            String b = (String) params.get("search");
            byte[] a = b.getBytes();
            params.put("search", a);
            List list = forYounyService.getSeachList(params);
            return R.ok(msg, code).put("list", list).put("nextPage", params.get("nextPage"));
        } else {
            Util.SetPage(params);
            String b = (String) params.get("search");
            byte[] a = b.getBytes();
            params.put("search", a);
            List list = personalService.getSeachList(params);
            return R.ok(msg, code).put("list", list);
        }
    }


    @Login
    @PostMapping("getMySchoolListByUserId")
    @ApiOperation("获取同校列表")
    public R getMySchoolListByUserId(@RequestBody Map<String, Object> params, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        params.put("userId", userId);
        UserEntity userEntity = userService.getUserByUserId(userId);
        List<Long> schoolUserId = userService.getSameSchoolUserIds(userEntity.getSchoolId());
        String schoolUserIds = "";
        for (Long id : schoolUserId) {
            schoolUserIds = schoolUserIds + id + ",";
        }
        if (!schoolUserIds.equals(""))
            schoolUserIds = schoolUserIds.substring(0, schoolUserIds.length() - 1);
        params.put("schoolUserIds", schoolUserIds);
        List<ForYounyEntity> forYounyEntityList;
        if (schoolUserIds.equals("")) {
            forYounyEntityList = new ArrayList<>();
        } else {
            forYounyEntityList = forYounyService.getMySchoolListByUserId(params);
        }
        List<ForYounyEntity> returnFor = new ArrayList<>();
        int limit = Integer.parseInt((String) params.get("limit"));
        if (forYounyEntityList.size() < limit) {
            limit = forYounyEntityList.size();
        }
        for (int i = 0; i < limit; i++) {
            int j = (int) (1 + Math.random() * (limit - 1 + 1));
            returnFor.add(forYounyEntityList.get(j - 1));
        }
        return R.ok(msg, code).put("list", returnFor);
    }


    @Login
    @PostMapping("getListByUserId")
    @ApiOperation("获取关注列表")
    public R getListByUserId(@RequestBody Map<String, Object> params, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        params.put("userId", userId);
        List<ForYounyEntity> forYounyEntityList = forYounyService.getOurFollowList(params);
        List<ForYounyEntity> returnFor = new ArrayList<>();
        int limit = Integer.parseInt((String) params.get("limit"));
        if (forYounyEntityList.size() < limit) {
            limit = forYounyEntityList.size();
        }
        for (int i = 0; i < limit; i++) {
            int j = (int) (1 + Math.random() * (limit - 1 + 1));
            returnFor.add(forYounyEntityList.get(j - 1));
        }
        return R.ok(msg, code).put("list", returnFor);
    }

    @Login
    @PostMapping("getOurList")
    @ApiOperation("获取信息列表")
    public R getOurList(@RequestBody Map<String, Object> params, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        params.put("userId", userId);
        List<ForYounyEntity> forYounyEntityList = forYounyService.getOurList(params);
        return R.ok(msg, code).put("list", forYounyEntityList);
    }

    @Login
    @GetMapping("getForYoungEntiyById")
    @ApiOperation("获取单个信息")
    public R getForYoungEntiyById(Integer id, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        ForYounyEntity forYounyEntity = forYounyService.getForYoungEntiyById(id, userId);
        List list = new ArrayList();
        list.add(forYounyEntity);
        return R.ok(msg, code).put("list", list);
    }

    @Login
    @PostMapping("reply")
    @ApiOperation("回复")
    public R reply(@RequestBody ForYoungReply forYoungReply, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        //1获取用户信息
        UserEntity userEntity = userService.getUserByUserId(userId);
        //2讲回复保存
        forYoungReply.setUserNameB(userEntity.getNickNameB());
        /**
         * 过滤敏感字符
         */
        String str = wordFilter(forYoungReply.getContent());
        forYoungReply.setContentB(str.getBytes());
        forYoungReply.setUserId(Math.toIntExact(userId));
        forYoungReply.setUserName(new String(userEntity.getNickNameB(), "utf-8"));
        forYoungReply.setUserHeadImage(userEntity.getHeadImg());
        forYoungReply.setId(forYounyService.saveReply(forYoungReply));
        forYoungReply.setCreateTime(new Date());
        //3获取当前评论，
        ForYoungComment forYoungComment = forYounyService.getCommentById(forYoungReply.getCommentId());
        //4看是否有回复
        if (forYoungComment.getFirstReplyUserId() == null) {
            forYoungComment.setFirstCreateTime(new Date());
            forYoungComment.setFirstReplyId(forYoungReply.getId());
            forYoungComment.setFirstReplyUserId(forYoungReply.getUserId());
            forYoungComment.setFirstReplyUserNickNameB(forYoungReply.getUserNameB());
            forYoungComment.setFirstReplyContentB(forYoungReply.getContentB());
        } else if (forYoungComment.getSecondReplyUserId() == null) {
            forYoungComment.setSecondReplyId(forYoungReply.getId());
            forYoungComment.setSecondCreateTime(new Date());
            forYoungComment.setSecondReplyUserId(forYoungReply.getUserId());
            forYoungComment.setSecondReplyUserNickNameB(forYoungReply.getUserNameB());
            forYoungComment.setSecondReplyContentB(forYoungReply.getContentB());
        }

        forYounyService.updateComment(forYoungComment);

        Map<String, String> map = new HashMap<>();
        map.put(ConstantConfig.PUSH_TAG, "YOUNG_COMMENT_REPLY");
        map.put(ConstantConfig.YOUNG_COMMENT_ID, forYoungComment.getId() + "");
        map.put(ConstantConfig.YOUNG_ID, forYoungComment.getForYoungId() + "");
        map.put(ConstantConfig.COMMENT_USER_HEAD, forYoungComment.getUserHeadImage());
        map.put(ConstantConfig.COMMENT_USER_NAME, new String(forYoungComment.getUserNameB()));
        map.put(ConstantConfig.COMMENT_CONTENT, new String(forYoungComment.getContentB()));
        map.put(ConstantConfig.COMMENT_TIME, new SimpleDateFormat().format(forYoungComment.getCreateTime()));

        Jdpush.sendAliasPush(ConstantConfig.APP_KEY, ConstantConfig.MASTER_SECRET,
                forYoungComment.getUserId() + "", "@ " + new String(userEntity.getNickNameB()) + " 回复了你的 " + new String(forYoungComment.getContentB()),
                map);


        return R.ok(msg, code).put("forYoungReply", forYoungReply);
    }

    @Login
    @PostMapping("comment")
    @ApiOperation("评论")
    public R comment(@RequestBody ForYoungComment forYoungComment, @ApiIgnore @RequestAttribute("userId") Long userId) {
        int code = 100;//保存成功
        String msg = "";
        //1获取用户信息
        UserEntity userEntity = userService.getUserByUserId(userId);  //评论人的id
        //2讲评论保存
        forYoungComment.setUserId(userId);
        forYoungComment.setUserNameB(userEntity.getNickNameB());

        /**
         * 过滤敏感字符
         */
        String str = wordFilter(forYoungComment.getContent());
        forYoungComment.setContentB(str.getBytes());
        if (userEntity.getHeadImg() != null)
            forYoungComment.setUserHeadImage(userEntity.getHeadImg());
        forYoungComment.setId(Math.toIntExact(forYounyService.savaForYoungComment(forYoungComment)));
        //3获取当前数据，
        ForYounyEntity forYounyEntity = forYounyService.getForyoungById(forYoungComment.getForYoungId());
        forYoungComment.setUserName(new String(forYoungComment.getUserNameB()));
        forYoungComment.setCreateTime(forYounyEntity.getCreateTime());

//        //4看是否是第一条
//        if(forYounyEntity.getFirstCommentId()==null){
        //5没有评论过，保存到第一条
        forYounyEntity.setFirstCommentId(Math.toIntExact(forYoungComment.getId()));
        forYounyEntity.setFirstCommentUserNameB(forYoungComment.getUserNameB());
        forYounyEntity.setFirstCommentContentB(forYoungComment.getContentB());
        forYounyEntity.setFirstCommentUserId(Math.toIntExact(userId));
        //    }
        forYounyService.saveFirstComment(forYounyEntity);


        Map<String, String> map = new HashMap<>();
        map.put(ConstantConfig.PUSH_TAG, "YOUNG_COMMENT");
        map.put(ConstantConfig.YOUNG_ID, forYounyEntity.getId() + "");

        Jdpush.sendAliasPush(ConstantConfig.APP_KEY, ConstantConfig.MASTER_SECRET,
                forYounyEntity.getUserId() + "", "@ " + new String(userEntity.getNickNameB()) + " 评论了你的 " + new String(forYounyEntity.getTitleB()), map);


        return R.ok(msg, code).put("forYoungComment", forYoungComment);
    }


    /**
     * 过滤敏感字符
     *
     * @param str
     */
    public String wordFilter(@RequestBody String str) {
        SensitiveWordFilter sw = new SensitiveWordFilter();
        sw.InitializationWork();
        long startNumer = System.currentTimeMillis();
        System.out.println("被检测字符长度:" + str.length());
        str = sw.filterInfo(str);
        long endNumber = System.currentTimeMillis();
        System.out.println("耗时(毫秒):" + (endNumber - startNumer));
        System.out.println("过滤之后:" + str);
        return str;
    }


    @Login
    @PostMapping("saveImgs")
    @ApiOperation("保存图片")
    public R saveImgs(@RequestParam("params") List<MultipartFile> params) {
        int code = 100;//保存成功
        String msg = "";
        //File file= (File) params.get("params");
        System.out.println("");
        String returnUrl = "";
        try {
            for (MultipartFile file : params) {
                Map<String, Object> param = new HashMap<String, Object>();
                String name =
                        //UUID.randomUUID().toString().replaceAll("\\-", "")+
                        file.getOriginalFilename();

                param.put("name", name);
                param.put("buffer", file.getBytes());
                Integer imgId = forYounyService.upload(param);
                System.out.println(imgId);
                returnUrl = returnUrl + contant.getImgurl() + imgId + ";";
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return R.ok(msg, code).put("url", returnUrl);
    }

    @Login
    @PostMapping("saveData")
    @ApiOperation("保存信息")
    public R saveData(@RequestBody ForYounyEntity forYounyEntity, @ApiIgnore @RequestAttribute("userId") Long userId) throws UnsupportedEncodingException {
        int code = 100;//保存成功
        String msg = "";
        UserEntity u = userService.getUserByUserId(userId);
        //forYounyEntity.setNackName(new String(u.getNickNameB(),"UTF-8"));
        forYounyEntity.setNickNameB(u.getNickNameB());
        /**
         * 过滤敏感字符
         */
        String str = wordFilter(forYounyEntity.getTitle());
        forYounyEntity.setTitleB(str.getBytes());
        forYounyEntity.setTitle("");
        forYounyEntity.setHeadImg(u.getHeadImg());
        forYounyEntity.setUserId(userId);
        forYounyService.saveData(forYounyEntity);
        List<String> strings = new ArrayList<>();
        strings.add(userId+"");

        Jdpush.sendTAagsPush(ConstantConfig.APP_KEY, ConstantConfig.MASTER_SECRET,
                "您关注的 @ " + new String(u.getNickNameB()) + " 发布了一篇新笔记,快来一起看看吧!~",
                strings,new HashMap<>());


        return R.ok(msg, code);
    }

    /**
     * 获取我的粉丝列表 并判断两人之间的关系  1 2 3 状态
     */
    public List getMyFans(long userId) throws UnsupportedEncodingException {
        Map map = new HashMap();
        map.put("userId", userId);

        List list = personalService.getMyFansList(map);

        for (int i = 0; i < list.size(); i++) {
            AttentionAndFansDto a = (AttentionAndFansDto) list.get(i);
            a.setNickName(new String(a.getNickNameB()));
        }
        return list;
    }


    @RequestMapping("/getimage/{id}")
    public @ResponseBody
    Map<String, Object> getimage(@PathVariable("id") Integer id, HttpServletResponse response) throws Exception {
        MysqlOssEntity m = forYounyService.getImgById(id);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + m.getName());
        ServletOutputStream toClient = response.getOutputStream(); //得到向客户端输出二进制数据的对象
        toClient.write(m.getImg());  //输出数据
        toClient.flush();
        toClient.close();
        return null;
    }

    /**
     * 读取文件
     */
    @RequestMapping("/file/{name}")
    public @ResponseBody
    Map<String, Object> file(@PathVariable("name") String name, HttpServletResponse response) throws Exception {
        MysqlOssEntity m = forYounyService.getImgByName(name);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + m.getName());
        ServletOutputStream toClient = response.getOutputStream(); //得到向客户端输出二进制数据的对象
        toClient.write(m.getImg());  //输出数据
        toClient.flush();
        toClient.close();
        return null;
    }


    @Login
    @PostMapping("toLike")
    @ApiOperation("点赞，取消点赞")
    public R toLike(@RequestBody Map params, @ApiIgnore @RequestAttribute("userId") Long userId) {
        int code = 100;//保存成功
        String msg = "";
        params.put("userId", userId);
        int b = forYounyService.toLike(params);

        return R.ok(msg, code).put("isLike", b);
    }

    @Login
    @PostMapping("toCollection")
    @ApiOperation("收藏，取消收藏")
    public R toCollection(@RequestBody Map params, @ApiIgnore @RequestAttribute("userId") Long userId) {
        int code = 100;//保存成功
        String msg = "";
        params.put("userId", userId);
        int b = forYounyService.toCollection(params);

        return R.ok(msg, code).put("isCollection", b);
    }

    @Login
    @PostMapping("toCommentLike")
    @ApiOperation("评论点赞，取消点赞")
    public R toCommentLike(@RequestBody Map params, @ApiIgnore @RequestAttribute("userId") Long userId) {
        int code = 100;//保存成功
        String msg = "";
        params.put("userId", userId);
        int b = forYounyService.toCommentLike(params);

        return R.ok(msg, code).put("isLike", b);
    }

    @Login
    @PostMapping("toReplyLIke")
    @ApiOperation("回复点赞，取消点赞")
    public R toReplyLIke(@RequestBody Map params, @ApiIgnore @RequestAttribute("userId") Long userId) {
        int code = 100;//保存成功
        String msg = "";
        params.put("userId", userId);
        int b = forYounyService.toReplyLIke(params);

        return R.ok(msg, code).put("isLike", b);
    }


    /**
     * 获取我的学习分享
     *
     * @param map
     * @return
     */
    @Login
    @PostMapping("getMyStudyShare")
    @ApiOperation("获取我的学习分享")
    public R getMyStudyShare(@RequestBody Map map) {
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId", userId);

        List list = forYounyService.getMyStudyShare(map);
        if (list.size() == 0) {
            return R.ok("主人您还没有分享最近学习状况呢~", 100).put("list", list);
        }
        for (int s = 0; s < list.size(); s++) {
            ForYounyEntity forYounyEntity = (ForYounyEntity) list.get(s);
            try {
                if (forYounyEntity.getImgs() != null) {
                    String[] imgsList = forYounyEntity.getImgs().split(";");
                    String[] wh = forYounyEntity.getImgswh().split(";");
                    List<ImgEntiy> imgEntiys = new ArrayList<>();
                    for (int i = 0; i < imgsList.length; i++) {
                        ImgEntiy imgEntiy = new ImgEntiy();
                        String[] whh = wh[i].split(":");
                        imgEntiy.setImgUrl(imgsList[i]);
                        imgEntiy.setWidth(whh[0]);
                        imgEntiy.setHeigh(whh[1]);
                        imgEntiys.add(imgEntiy);
                    }
                    forYounyEntity.setImgList(imgEntiys);
                }
            } catch (Exception e) {

            }

        }
        return R.ok("查询成功~", 100).put("list", list);
    }


    /**
     * 获取我的致青春
     */
    @Login
    @PostMapping("getMyForYoung")
    @ApiOperation("获取我的致青春")
    public R getMyForYoung(@RequestBody Map map) throws UnsupportedEncodingException, ParseException {
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId", userId);
        List<ForYounyEntity> list = forYounyService.getMyForYoung(map);

        if (list.size() == 0) {
            return R.ok("主人您还没有发布您的致青春呢~", 100).put("list", list);
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //System.out.println(sf.format(list.get(1).getCreateTime()));
        return R.ok("查询成功~", 100).put("list", list);
    }

    /**
     * 我的致青春收藏
     */
    @Login
    @PostMapping("getMyForYoungCollection")
    @ApiOperation("我的致青春收藏")
    public R getMyForYoungCollection(@RequestBody Map map) throws UnsupportedEncodingException {
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId", userId);

        List list = forYounyService.getMyForYoungCollection(map);
        return R.ok("查询成功~", 100).put("list", list);
    }


    /**
     * 刪除我的致青春
     */
    @Login
    @PostMapping("delMyForYoung")
    @ApiOperation("刪除我的致青春")
    public R delMyForYoung(@RequestBody Map map) {
        String token = (String) map.get("token");
        Long userId = tokenService.getUserIdByToken(token);
        map.put("userId", userId);
        if (map.get("forYoungId") == null) {
            return R.error(101, "请选择要删除的致青春");
        }

        forYounyService.delForYoung(map);

        return R.ok("刪除成功", 100);
    }
}





